<template>
  <section class="query">
    <div class="bg"></div>
    <div class="container">
      <div class="card" style="padding:16px;">
        <h1 class="title">{{ category }}</h1>
        <p style="margin:0 0 16px;color:var(--muted);">请填写您的出生信息后点击查询</p>

      <div class="row row-2">
        <div class="field">
          <label for="user_birthday_date" class="ink-label">出生年月</label>
          <input id="user_birthday_date" v-model="form.user_birthday_date" class="input" type="date" />
        </div>
        <div class="field">
          <label for="user_birthday_time" class="ink-label">出生时间</label>
          <input id="user_birthday_time" v-model="form.user_birthday_time" class="input" type="time" />
        </div>
      </div>

      <div class="row">
        <div class="field">
          <label for="user_sex" class="ink-label">性别</label>
          <select id="user_sex" v-model="form.user_sex" class="select">
            <option value="男">男</option>
            <option value="女">女</option>
          </select>
        </div>
      </div>

      <div class="row row-2">
        <div class="field">
          <label class="ink-label" for="province">出生地址（省）</label>
          <select id="province" v-model="form.province" class="select">
            <option value="">请选择省</option>
            <option v-for="p in provinces" :key="p.name" :value="p.name">{{ p.name }}</option>
          </select>
        </div>
        <div class="field">
          <label class="ink-label" for="city">出生地址（市）</label>
          <select id="city" v-model="form.city" class="select" :disabled="!form.province">
            <option value="">请选择市</option>
            <option v-for="c in cities" :key="c" :value="c">{{ c }}</option>
            <option v-if="form.province" value="其他">其他</option>
          </select>
          <small v-if="form.province && cities.length === 0" class="tip">该省暂无城市数据</small>
        </div>
      </div>

      <div class="actions">
        <button class="btn big" :disabled="loading" @click="onSubmit" v-if="!resultId">
          <span v-if="!loading">查询</span>
          <span v-else class="loading-inline">
            <span class="spinner" aria-hidden="true"></span>
            查询中…
          </span>
        </button>
      </div>

      <div v-if="loading" class="loading">
        <div class="spinner" aria-hidden="true"></div>
        <span>正在分析，请稍候…</span>
      </div>

      <div v-if="result" class="card result">
        <div class="result-content" :class="{ clipped: shouldClip }">
          <h2 style="margin:0 0 8px;">查询结果</h2>
          <div class="result-body" v-html="cleanResult"></div>
        </div>
        <div v-if="resultId" class="pay-wrap">
          <button class="btn big pay-btn" @click="onPay">支付</button>
          <p class="pay-tip">支付后可查看完整内容</p>
        </div>
      </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import { makeUrl } from '../lib/config'
import { provinces } from '../lib/areas'
import { getCsrfToken } from '../lib/csrf'

const route = useRoute()
const router = useRouter()
const category = computed(() => route.query?.type || '')
// 当 category 为空时，返回首页
watch(category, (val) => {
  if (!val) router.replace('/');
}, { immediate: true })

// 统一与模板的 v-model 字段名保持一致
const form = ref({
  user_birthday_date: '',
  user_birthday_time: '',
  user_sex: '男',
  province: '',
  city: '',
})
const loading = ref(false)
const result = ref('')
const paid = ref(false)
// 保存后端返回的 id，用于后续 GET 请求
const resultId = ref('')
// 仅在后端返回有效查询 ID（视为有真实结果）时启用虚化剪裁
const shouldClip = computed(() => Boolean(resultId.value))

// 基础清洗：移除潜在危险标签与事件属性，仅保留安全内容
const sanitizeHtml = (html) => {
  const container = document.createElement('div')
  container.innerHTML = html || ''
  container.querySelectorAll('script, iframe, object, embed, link[rel="import"]').forEach(el => el.remove())
  container.querySelectorAll('*').forEach(el => {
    Array.from(el.attributes).forEach(attr => {
      if (/^on/i.test(attr.name) || attr.name === 'style') el.removeAttribute(attr.name)
    })
  })
  return container.innerHTML
}

// 渲染结果：如果包含 HTML 标签则以清洗后的 HTML 渲染，否则转行成 <br>
const cleanResult = computed(() => {
  // 去掉所有 # 号
  const s = String(result.value ?? '').replace(/#/g, '')
  const hasTag = /<\w+[\s\S]*>/i.test(s)
  if (hasTag) return sanitizeHtml(s)
  const withNewlines = s.replace(/\\n/g, '\n')
  return withNewlines.replace(/\n/g, '<br>')
})

// 城市联动：根据省份计算城市列表
const cities = computed(() => {
  const p = provinces.find(x => x.name === form.value.province)
  return p ? p.cities : []
})
// 省份改变时重置市级选择
watch(() => form.value.province, () => {
  form.value.city = ''
})

const onSubmit = async () => {
  result.value = ''
  paid.value = false
  // 重置查询标识，避免错误或空结果时仍显示支付按钮
  resultId.value = ''

  // 简单校验
  const errors = []
  if (!form.value.user_birthday_date) errors.push('请填写出生年月')
  if (!form.value.user_birthday_time) errors.push('请填写出生时间')
  if (!form.value.user_sex) errors.push('请选择性别')
  if (!form.value.province) errors.push('请选择出生省份')
  if (!form.value.city) errors.push('请选择出生城市')
  if (errors.length) {
    result.value = errors.join('、')
    paid.value = true
    return
  }

  loading.value = true
  try {
    const payload = { ...form.value, type: category.value }
    const formData = new FormData()
    Object.entries(payload).forEach(([k, v]) => formData.append(k, v ?? ''))
    // 省市拼接为一个字符串，写入 user_address（仅在有值时用 - 连接）
    const userAddress = [form.value.province, form.value.city].filter(Boolean).join('-')
    formData.append('user_address', userAddress)
    // 先调用后端生成 CSRF token
    const csrfUrl = await makeUrl('api/csrf/')
    let csrfToken = ''
    try {
      const csrfResp = await axios.get(csrfUrl, { withCredentials: true })
      // 优先尝试响应体中的常见字段；否则从 Cookie 读取
      csrfToken =
        (csrfResp.data?.csrfToken ?? csrfResp.data?.token ?? csrfResp.data?.csrf ?? '') ||
        getCsrfToken() ||
        ''
    } catch (e) {
      // 兜底：若接口调用失败，尝试直接从 Cookie 读取
      csrfToken = getCsrfToken() || ''
    }
    console.log(csrfToken)
    if (csrfToken) formData.append('csrfmiddlewaretoken', csrfToken)
    // 调试：打印提交的表单字段（不再中断请求）
    for (const [k, v] of formData.entries()) {
      console.log('FormData', k, v)
    }
    // 调试：打印提交的表单字段
    for (const [k, v] of formData.entries()) {
      console.log('FormData', k, v)
    }
    // 不手动设置 Content-Type，交由浏览器附带正确的 multipart 边界
    const url = await makeUrl('/api/userinfo/')
    const axiosConfig = { withCredentials: true }
    if (csrfToken) {
      axiosConfig.headers = { 'X-CSRFToken': csrfToken }
    }
    const { data } = await axios.post(url, formData, axiosConfig)
    console.log('POST Response', data)
    // 保存接口返回的 id
    resultId.value = String((data && (data.data_id ?? data.data?.id)) || '')
    // 直接使用后端返回的内容；如为 HTML 则走清洗渲染
    result.value = data?.result ?? (typeof data === 'string' ? data : JSON.stringify(data, null, 2))
  } catch (err) {
    result.value = err?.response?.data?.message || err.message || '查询失败'
  } finally {
    loading.value = false
  }
}

const reset = () => {
  form.value = { date: '', time: '', gender: '男', province: '', city: '' }
  result.value = ''
}

const onPay = async () => {
  try {
    if (!resultId.value) throw new Error('缺少查询 ID')
    // 以 GET 方式携带 id 到后端（使用查询参数）
   const url = await makeUrl(`/api/alipay/`)
    const { data } = await axios.get(url, { params: { data_id: resultId.value } })
    console.log('Alipay Response', data)
    // 后端可能直接返回跳转 URL 字符串，或对象中包含 redirect_url
    const redirect = typeof data === 'string' ? data : (data?.redirect_url || data?.url || '')
    if (redirect) {
      // 不要改动支付宝网关签名参数；如需携带标识，请后端通过 passback_params 传递
      // 前端仅做原样跳转，避免新增参数导致验签失败
      window.location.href = redirect
    }
  } catch (err) {
    alert(err?.response?.data?.message || err.message || '请求失败')
  }
}
</script>

<style scoped>
.query {
  position: relative;
  min-height: 100vh;
  overflow: hidden;
}
.bg {
  position: absolute;
  inset: 0;
  background-image: url('/images/bg.jpg');
  background-position: center;
  background-size: cover;
  background-repeat: no-repeat;
  filter: blur(3px) saturate(1.05) brightness(0.96);
  opacity: 0.55;
  transform: scale(1.06);
  will-change: transform;
  z-index: 0;
}
.bg::after {
  content: '';
  position: absolute;
  inset: 0;
  background: radial-gradient(ellipse at center, rgba(255,255,255,0.80) 0%, rgba(255,255,255,0.90) 55%, rgba(255,255,255,0.96) 100%);
}
.container { position: relative; z-index: 1; }

.ink-label {
  font-family: 'Ma Shan Zheng','Zhi Mang Xing','Long Cang','KaiTi','STKaiti','SimSun',sans-serif;
  color: #0f172a;
  font-weight: 700;
  margin-bottom: 6px;
}

/* 统一各行间距与字段布局 */
.row {
  display: flex;
  gap: 12px;
  margin: 12px 0;
}
.row .field { flex: 1; }
.row-2 .field { flex: 1; }
.field { display: flex; flex-direction: column; }

.actions {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}
.btn.big {
  font-size: 18px;
  padding: 14px 24px;
  min-width: 180px;
  border-radius: 999px;
}
.loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-top: 12px;
  color: var(--muted);
}
.loading-inline { display: inline-flex; align-items: center; gap: 8px; }
.spinner {
  width: 22px; height: 22px;
  border: 3px solid rgba(14,165,233,.25);
  border-top-color: var(--primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }

.result { margin-top: 16px; }
.result-content { padding: 12px 16px; }
.result-content pre {
  white-space: pre-wrap;
  word-break: break-word;
  margin: 0;
}
.result-content.clipped {
  max-height: 260px;
  overflow: hidden;
  position: relative;
}
.result-content.clipped::after {
  content: '';
  position: absolute;
  left: 0; right: 0; bottom: 0;
  height: 80px;
  background: linear-gradient(to bottom, rgba(255,255,255,0), #fff);
}
.pay-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px 16px 16px;
}
.pay-btn { background: #111; }
.pay-tip { margin: 0; color: var(--muted); font-size: 13px; }

/* —— 道家玄学风格增强 —— */
.title {
  margin: 0 0 8px;
  font-family: 'Ma Shan Zheng','Zhi Mang Xing','Long Cang','KaiTi','STKaiti',serif;
  color: #3a2a1a;
  letter-spacing: 2px;
  font-size: 28px;
}
.card {
  background: #fff8e9;
  border-radius: 16px;
  border: 1px solid rgba(58,42,26,0.25);
  box-shadow: 0 10px 30px rgba(58,42,26,.12);
  position: relative;
}
.card::before {
  content: '';
  position: absolute;
  inset: 0;
  pointer-events: none;
  background: repeating-linear-gradient(0deg, transparent 0, transparent 10px, rgba(0,0,0,0.02) 11px),
              radial-gradient(circle at 20% 10%, rgba(221,190,117,.12), transparent 60%),
              radial-gradient(circle at 80% 90%, rgba(221,190,117,.08), transparent 60%);
  border-radius: 16px;
}
.input, .select {
  background: #fffdf7;
  border: 1px solid rgba(58,42,26,0.25);
}
.actions .btn.big {
  background: linear-gradient(180deg, #e7c96a, #d4af37);
  color: #2b1c12;
  box-shadow: 0 6px 16px rgba(212,175,55,.35);
}
.pay-btn { background: #e53935; color: #fff; }
.tip { color: #8b5e34; }
</style>